//
//  UserAccountViewModel.swift
//  微博
//
//  Created by mac on 15/12/16.
//  Copyright © 2015年 itcats. All rights reserved.
//

import UIKit
import AFNetworking
class UserAccountViewModel: NSObject {

    var userAccount: UserAccount?
    override init() {
        userAccount = UserAccount.loadAccount()
        super.init()
    }
    //计算性属性
    var userLogin:Bool {
    return userAccount?.access_token != nil
    }
    var userName: String?{
    return userAccount?.name
    }
    
    //用户头像的URL
    var headURL: NSURL? {
    let url = NSURL(string: userAccount?.avatar_large ?? "")
        return url
    }
    var token: String? {
        return userAccount?.access_token
    }
    
     func loadAccessToken(code:String,finished: (isSuccess:Bool) ->()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
        let AFN = AFHTTPSessionManager()
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        AFN.POST(urlString, parameters: parameters, progress: { (p) -> Void in
            print(p)
            }, success: { (_, result) -> Void in
                if let dict = result as? [String : AnyObject]{
                    let userAccount = UserAccount(dict: dict)
                    self.loadUserInfo(userAccount, finished: finished)
                }
            }) { (_, error) -> Void in
                print(error)
                finished(isSuccess: false)
        }
    }
    //获取用户信息
    private func loadUserInfo(account: UserAccount,finished:(isSuccess:Bool) ->()){
        let urlString = "https://api.weibo.com/2/users/show.json"
        if let token = account.access_token,userId = account.uid{
            let parameters = ["access_token":token,"uid":userId]
            let AFN = AFHTTPSessionManager()
            AFN.GET(urlString, parameters: parameters, progress: { (_) -> Void in
                
                }, success: { (_, result) -> Void in
                    if let dict = result{
                        let avatar_large = dict["avatar_large"] as! String
                        let name = dict["name"] as! String
                        
                        account.name = name
                        account.avatar_large = avatar_large
                        
                        account.saveAccount()
                       finished(isSuccess: true)
                    }
                }){
                    (_, error) -> Void in
                    print(error)
                    finished(isSuccess: false)
            }
        }
        
    }
    

    
}
